package com.allwees.bs.core.modelbase.req;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.allwees.core.common.util.StringUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

import java.util.ArrayList;
import java.util.List;

/**
 * 查询请求基类
 *
 * @author yangylsky
 * @since 2019-12-23
 *
 * @param <T>
 */
@Data
@EqualsAndHashCode(callSuper = true)
@ToString
@Accessors(chain = true)
public abstract class QueryReq<T> extends Req implements Queryable<T> {
	/**
	 * 精确或模糊查询关键字
	 */
	protected String q;

	/**
	 * 格式: ["column1:asc|desc", "column2:asc|desc", ...]。示例: ["createAt:desc", "name:asc"]
	 */
	protected String[] sort = new String[] {"id:desc"};

	@Override
	protected void completion() {
		super.completion();

		setQ(StringUtils.isBlank(getQ()) ? null : q.trim());
	}

	protected List<Order> orders() {
		List<Order> orders = new ArrayList<>();
		if(ArrayUtils.isNotEmpty(sort)) {
			for(String sortItem : sort) {
				String[] sArr = StringUtils.split(sortItem, ":");
				Direction direction = sArr.length > 1 ? Direction.fromString(sArr[1].trim()) : Direction.DESC;
				Order order = new Order(direction, StringUtil.humpToSeparate(sArr[0].trim()));
				orders.add(order);
			}
		}
		return orders;
	}

	/**
	 *
	 */
	@Override
	public final QueryWrapper<T> toQueryWrapper() {
		QueryWrapper<T> queryWrapper = new QueryWrapper<>();
		buildQuery(queryWrapper);
		for(Order order : orders()) {
			queryWrapper.orderBy(order != null, order.isAscending(), StringUtil.humpToSeparate(order.getProperty()));
		}
		return queryWrapper;
	}

	/**
	 *
	 * @param queryWrapper
	 * @return
	 */
	protected void buildQuery(QueryWrapper<T> queryWrapper) {
	}
}
